package com.laze.mywanandroid.ui.main.fragment.project


import androidx.lifecycle.MutableLiveData
import com.chad.library.adapter.base.loadmore.LoadMoreStatus
import com.laze.mywanandroid.base.BaseViewModel
import com.laze.mywanandroid.bean.PageData
import com.laze.mywanandroid.bean.Project
import com.laze.mywanandroid.bean.ProjectTree

class ProjectViewModel : BaseViewModel() {

    companion object {
        const val INIT_PAGE = 1
    }

    private val response by lazy { ProjectRepository() }
    var isOpen: MutableLiveData<Boolean> = MutableLiveData(false)
    val projectTree: MutableLiveData<MutableList<ProjectTree>> = MutableLiveData()
    val projectList: MutableLiveData<PageData<Project>> = MutableLiveData()
    var projectId: MutableLiveData<Int> = MutableLiveData()
    val loadMoreStatus = MutableLiveData<LoadMoreStatus>()

    //页码起始为1
    var page = INIT_PAGE

    fun initProjectTree() {
        launch(
            block = {
                projectTree.value = response.getProjectTree()
                projectTree.value?.let {
                    projectId.value = it[0].id
                    getProjectList(projectId.value!!)
                }
            },
            error = {
                toast(it.message.toString())
            }
        )
    }

    fun changeTree() {
        isOpen.value = !isOpen.value!!
    }

    /**
     * 变更ID
     */
    fun changeProjectId(selectId: Int){
        projectId.value = selectId
        getProjectList(projectId.value!!)
    }

    /**
     * 获取项目列表
     */
    private fun getProjectList(projectId: Int) {
        launch(
            block = {
                page = INIT_PAGE
                projectList.value = response.getProject(projectId, page)
            },
            error = {
                toast(it.message.toString())
            }
        )
    }

    /**
     * 加载更多项目
     */
    fun loadMoreProject() {
        loadMoreStatus.value = LoadMoreStatus.Loading
        launch(
            block = {
                val newList = response.getProject(projectId.value!!, page+1)
                page = newList.curPage
                val currentList = projectList.value ?: newList
                currentList.datas.addAll(newList.datas)
                projectList.value = currentList
                loadMoreStatus.value = if (newList.offset >= newList.total) {
                    LoadMoreStatus.End
                } else {
                    LoadMoreStatus.Complete
                }
            },
            error = {
                page = INIT_PAGE
                loadMoreStatus.value = LoadMoreStatus.Fail
            }
        )
    }
}